package chagine.core.id.ider.impl;


import chagine.core.id.IDService;
import chagine.core.id.ider.SnowFlake;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * com.guantong.seeing.ider.impl.IDImpl
 * Created by 王彬安（wba）on 2017/8/9.
 */
@Slf4j
public class IDImpl implements IDService {

    /**
     * 机器ID,每个部署的服务这个ID必须不同，且小于31
     */
    private final int machineId;

    private final Map<Integer, SnowFlake> snowFlakeMap = new ConcurrentHashMap<>();

    public IDImpl(int machineId) {
        this.machineId = machineId;
    }

    private SnowFlake getSnowFlake(int idType) {
        SnowFlake snowFlake = snowFlakeMap.get(idType);
        if (snowFlake == null) {
            snowFlake = new SnowFlake(idType, machineId);
            snowFlakeMap.put(idType, snowFlake);
        }
        return snowFlake;
    }

    @Override
    public long getNextId(int idType) {
        SnowFlake snowFlake = getSnowFlake(idType);
        return snowFlake.nextId();
    }

    @Override
    public List<Long> getBatchIds(int idType, int count) {
        SnowFlake snowFlake = getSnowFlake(idType);
        List<Long> longList = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            Long id = snowFlake.nextId();
            longList.add(id);
        }
        return longList;
    }

}
